<?php
if(!defined('MY_ROOT'))
{throw new Exception('Access Denied');}
/* File weixin.php
* Creator: zhuchen115 (at) gmail.com
* Version: 0.0.1
*/
class weixin{
	
	private $appid;
	private $appsec;
	private $token;
	private $reqtk;

	function __construct($config){
		$this->appid=$config['appid'];
		$this->appsec=$config['appsec'];
		$this->reqtk=$config['token'];
	}
	private function get_token(){
		clearstatcache();
		$tcache=MY_ROOT.'/data/cache/wxtoken.cache';
		if((file_exists($tcache))&&(filemtime($tcache)<(time()+7200))){
			$this->token=file_get_contents($tcache);
			return file_get_contents($tcache);
		}
		else{
			$ch=curl_init();
			$api='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsec;
			curl_setopt($ch,CURLOPT_URL,$api);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			curl_setopt_array($ch,array(CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false));
			$res=curl_exec($ch);
			if(curl_errno($ch)){
			logerr('WXERR: CURL'.curl_error($ch),'weixin');
			throw new Exception('WXERR: CURL'.curl_error($ch));
			}
			$return=json_decode($res,true);
			
			if($return['errcode']!=0){
				logerr('WXERR:'.$return['errcode'],'weixin');
				debug_backtrace();
				throw new Exception('WXERR:'.$return['errcode']);
			}
			file_put_contents($tcache,$return['access_token']);
			$this->token=$return['access_token'];
			return $return['access_token'];
		}
	}
	function upload($file,$type){
		if($this->token==""){
		$this->get_token();
		}
		if(!in_array($type,array('image','voice','video','thumb'))){throw new Exception("WXERR: Upload File Type Not Supported");}
		$ch=curl_init();
		$api='http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token='.$this->token.'&type='.$type;
		$fp=curl_file_create($file);
		$data=array('media'=>$fp);
		curl_setopt($ch,CURLOPT_URL,$api);
		curl_setopt($ch,CURLOPT_POST,true);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$res=curl_exec($ch);
		echo $res;
		if(curl_errno($ch)){
		logerr('WXERR: CURL'.curl_error($ch),'weixin');
		throw new Exception('WXERR: CURL'.curl_error($ch));
		}
		$ret=json_decode($res);
		if($ret['errcode']!=0){
			logerr('WXERR:'.$ret['errcode'],'weixin');
			throw new Exception('WXERR:'.$ret['errcode']);
		}
		$ds['media_id']=$ret['media_id'];
		$ds['type']=$ret['type'];
		$ds['file']=$file;
		$ds['comment']='TYPE:'.$type.'UPLOAD:'.time();
		//DB::insert('wx_upload',$ds);
		return $ret;
	}
	function download($media,$save){
		//$ch=curl_init();
		$api='http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$this->token.'&media_id='.$media;
		return file_put_contents($save,@file_get_contents($api));
	}
	 function checkSignature($signature,$timestamp,$nonce){    		
	$token = $this->reqtk;
	$tmpArr = array($token, $timestamp, $nonce);
	sort($tmpArr);
	$tmpStr = implode( $tmpArr );
	$tmpStr = sha1( $tmpStr );
	if( $tmpStr == $signature ){
		return true;
	}else{
		return false;
	}
	}
	function getmsg(){
	$postdata=file_get_contents('php://input');
	$obj=simplexml_load_string($postdata,"SimpleXMLElement",LIBXML_NOCDATA);
	$ret['to']=trim($obj->ToUserName);
	$ret['from']=trim($obj->FromUserName);
	$ret['msgid']=trim($obj->MsgId);
	$ret['type']=trim($obj->MsgType);
	$ret['time']=trim($obj->CreateTime);
	switch ($ret['type']){
		case 'text':
			$ret['content']=trim($obj->Content);
			$cond['user']=$ret['from'];
			$cond['content']=$ret['content'];
			DB::insert('message',$cond);
			break;
		case 'image':
			$ret['mediaid']=$obj->MediaId;
			$ret['picurl']=$obj->PicUrl;
			break;
		case 'voice':
			$ret['mediaid']=$obj->MediaId;
			$ret['format']=$obj->Format;
			@$ret['content']=$obj->Recognition;
			break;
		case 'video':
			$ret['mediaid']=$obj->MediaId;
			$ret['thumb']=$obj->ThumbMediaId;
			break;
		case 'location':
			$ret['x']=$obj->Location_X;
			$ret['y']=$obj->Location_Y;
			$ret['scale']=$obj->Scale;
			$ret['label']=$obj->Label;
			break;
		case 'link':
			$ret['title']=$obj->Title;
			$ret['desc']=$obj->Description;
			$ret['url']=$obj->Url;
			break;
		case 'event':
			$this->event($obj,$ret);
			break;
		default:
			logerr('WXERR: Bad Request Type'.$ret['type'],'weixin');
	}
	$cond['user']=$ret['from'];
	return $ret;
	}
	function event($obj,&$ret){
		$arr=get_object_vars($obj);
		$ret['event']=$arr['Event'];
		//var_dump($arr);throw new Exception();
		switch ($arr['Event']){
			case 'subscribe':
				$ds['wxid']=$arr['FromUserName'];
				//DB::insert('wx_subscribe',$ds);
				if(isset($arr['EventKey'])){
				 $ret['eventkey']=sscanf($arr['EventKey'],"qrscene_%s");
				}
				break;
			case 'scan':
				$ret['eventkey']=$arr['EventKey'];
				break;
			case 'LOCATION':
				$ret['latitude']=$arr['Latitude'];
				$ret['longitude']=$arr['Longitude'];
				$ret['precision']=$arr['Precision'];
				break;
			case 'CLICK':
				$ret['eventkey']=$arr['EventKey'];
				break;
			default:
				logerr('WXERR: Bad Event Type'.$arr['event'],'weixin');
		}
	}
	function response($type,$content){
		global $_G;
		$smarty=$_G['hwnd']['smarty'];
		$content['time']=time();
		$content['type']=$type;
		$smarty->setCacheLifetime(0);
		$smarty->assign('content',$content);
		switch ($type){
			case 'text':
				$smarty->display('weixin/resp_text.tpl');
				break;
			case 'image':
				$smarty->display('weixin/resp_image.tpl');
				break;
			case 'voice':
				$smarty->display('weixin/resp_voice.tpl');
				break;
			case 'video':
				$smarty->display('weixin/resp_video.tpl');
				break;
			case 'music':
				$smarty->display('weixin/resp_music.tpl');
				break;
			case 'news':
				$smarty->display('weixin/resp_news.tpl');
				break;
			default:
			logerr('WXERR: Bad Input','Wexin');
			debug_print_backtrace();
			
		}
	}
	function send($to,$type,$content=array()){
		if($this->token==""){
		$this->get_token();
		}
		$ch=curl_init();
		$msg=array('touser'=>$to,'msgtype'=>$type);
		$msg=array_merge($msg,$content);
		$msg=json_encode($msg,JSON_FORCE_OBJECT);
		//echo $msg;
		curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->token);
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt_array($ch,array(CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false));
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
		return curl_exec($ch);
	}
	function get_menu(){
		if($this->token==""){
		$this->get_token();
		}
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->token);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$ct=curl_exec($ch);
		$cta=json_decode($ct,true);
		if($cta['errcode']!=0){
			echo $cta['errmsg'];
			return false;
		}else{
			return $cta;
			}
		
	}
	function save_menu($menu){
		if($this->token==""){
		$this->get_token();
		}
		$ch=curl_init();
		$data=json_encode($menu,JSON_UNESCAPED_UNICODE);
		curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->token);
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt_array($ch,array(CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false));
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$ct=curl_exec($ch);
		if(curl_errno($ch)){
		logerr('WXERR: CURL'.curl_error($ch),'weixin');
		//debug_print_backtrace();
		throw new Exception('WXERR: CURL'.curl_error($ch));
		}
		$cta=json_decode($ct,true);
		//var_dump($ct);
		if($cta['errcode']!=0){
			return false;
		}else{
		return true;
		}
	}
	function del_menu(){
		if($this->token==""){
		$this->get_token();
		}
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->token);
		curl_setopt_array($ch,array(CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false));
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$ct=curl_exec($ch);
		if(curl_errno($ch)){
		logerr('WXERR: CURL'.curl_error($ch),'weixin');
		//debug_print_backtrace();
		throw new Exception('WXERR: CURL'.curl_error($ch));
		}
		$cta=json_decode($ct,true);
		if($cta['errcode']!=0){
			return false;
		}else{
			return $cta;
			}
	}
	function create_group($name){
		if($this->token==""){
		$this->get_token();
		}
		$ch=curl_init();
		curl_setopt_array($ch,array(CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false));
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$this->token);
		$arr=array('group'=>array('name'=>$name));
		curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($arr));
		$ct=curl_exec($ch);
		if(curl_errno($ch)){
		logerr('WXERR: CURL'.curl_error($ch),'weixin');
		//debug_print_backtrace();
		throw new Exception('WXERR: CURL'.curl_error($ch));
		}
		$cta=json_decode($ct,true);
		if($cta['errcode']!=0){
			return false;
		}else{
			return $cta;
		}
	}
	
	
}
?>